$(function() {
	
	var notebookDiv = $('#notebook div');
	var noteDiv = $('#note div');
	var currentSavedNoteList = [];
	
	// Bind CRUD event of the notebook panel.
	$('#notebook').panel({
        tools: [{
            iconCls: 'icon-add',
            handler: function() {
            	notebookDialogHandler('Add')
            }
        }, {
            iconCls: 'icon-edit',
            handler: function() {
            	notebookDialogHandler('Edit')
            }
        }, {
            iconCls: 'icon-remove',
            handler: deleteNotebookHandler
        }]
	});
	
	// Get notebook list for the first time
	getNotebookListData();
	
	function notebookDialogHandler(dialogType) {
		var isShowDialog = true;
		if (dialogType == 'Edit') {
			var selectedItem = getSelectedNotebook();
			if (selectedItem) {
				var notebookNameHtml = selectedItem.html();
				$('#dialogNotebook input').val(notebookNameHtml.substring(notebookNameHtml.lastIndexOf('</span>') + 7));
			} else {
				isShowDialog = false;
				$.messager.alert('Prompt', 'Info: Select any notebook firstly.')
			}
		}
		if (isShowDialog) {
			$('#dialogNotebook').dialog({
				title: dialogType + ' notebook',
				width: 300,
				closed: false,
				cache: false,
				modal: true,
				resizable: false,
				draggable: false,
				buttons: [{
					iconCls: 'icon-save',
					text: 'Save',
					handler: function() {
						addOrUpdateNotebook(dialogType)
					}
				}],
				onClose: function() {
					$("#dialogNotebook form").form("clear");
				}
			});
			$('#dialogNotebook').window('center');
		}
	}
	
	function addOrUpdateNotebook(actionType) {
		if (actionType == 'Add') {
			var param = {
				notebookName: $('#dialogNotebook input').val()
			};
			$.post(config['NOTEBOOK_ADD_URL'], param, function(result) {
				if (result.succeeded) {
					$("#dialogNotebook form").form("clear");
					$('#dialogNotebook').window('close');
					// Refresh notebook list data.
					getNotebookListData();
				} else {
					$.messager.alert('Prompt', 'Error: ' + result.message);
				}
			});
			
		} else if (actionType == 'Edit') {
			var param = {
				notebookName: $('#dialogNotebook input').val()
			};
			$.post(config['NOTEBOOK_UPDATE_URL'] + getSelectedNotebook().data('id'), param, function(result) {
				if (result.succeeded) {
					$("#dialogNotebook form").form("clear");
					$('#dialogNotebook').window('close');
					// Refresh notebook list data.
					getNotebookListData();
				} else {
					$.messager.alert('Prompt', 'Error: ' + result.message);
				}
			})
		}
	}
	
	function deleteNotebookHandler() {
		var selectedItem = getSelectedNotebook();
		if (selectedItem) {
            $.messager.confirm('Confirm', 'Are you confirm this?', function(yes){
                if (yes){
                	$.get(config['NOTEBOOK_DELETE_URL'] + selectedItem.data('id'), function(result) {
        				if (result.succeeded) {
        					// Delete current notebook's note list
        					noteDiv.empty();
        					// Refresh notebook list data.
        					getNotebookListData();
        				} else {
        					$.messager.alert('Prompt', 'Error: ' + result.message);
        				}
        			});
                }
            });
		} else {
			$.messager.alert('Prompt', 'Info: Select any notebook firstly.')
		}
	}
	
	function getSelectedNotebook() {
		var selectedItem = undefined;
		if (notebookDiv.find('a')) {
			$.each(notebookDiv.find('a'), function(index, item) {
				if ($(item).hasClass('active')) {
					selectedItem = $(item);
				}
			});
		}
		return selectedItem;
	}
	
	// Get notebook list data.
	function getNotebookListData() {
		$.get(config['NOTEBOOK_LIST_URL'], function(data) {
			notebookDiv.empty();
			$.each(data, function(index, item) {
				notebookDiv.append('<a href="#" class="list-group-item" data-id="' + item.id + '"><span class="badge">' + 
						item.noteSum + '</span>' + item.notebookName + '</a>');
			});
			// Bind events of getting every notebook's note list.
			if (notebookDiv.find('a')) {
				notebookDiv.find('a').on('click', function(e) {
					e.preventDefault();
					$.each(notebookDiv.find('a'), function(index, item) {
						$(item).removeClass('active');
					});
					$(this).addClass('active');
					getNoteListData($(this).data('id'));
				});
			}
		});
	}
	
	// Get note list data.
	function getNoteListData(notebookId) {
		$.get(config['NOTE_LIST_URL'], {notebookId: notebookId}, function(noteList) {
			noteDiv.empty();
			currentSavedNoteList = [];
			$.each(noteList, function(index, item) {
				console.log(item);
				currentSavedNoteList.push(item);
				noteDiv.append(
					'<a href="#" class="list-group-item" data-id="' + item.id + '">' + 
						'<p class="list-group-item-heading"><b>' + item.title + '</b>' +
							'<span class="pull-right">' +
								'<span>创建时间: </span>' +
								'<span style="margin-right: 10px;">' + item.createDate + '</span>' +
								'<span>更新时间: </span>' +
								'<span>' + item.updateDate + '</span>' +
							'</span>' + 
						'</p>' +
						'<p class="list-group-item-text">' + getFixedContent(item.content) + '</p>' + 
					'</a>'
				);
			});
			// Bind events of selecting every note.
			if (noteDiv.find('a')) {
				noteDiv.find('a').on('click', function(e) {
					e.preventDefault();
					$.each(noteDiv.find('a'), function(index, item) {
						$(item).removeClass('active');
					});
					$(this).addClass('active');
				});
			}
		});
	}
	
	// Bind CRUD event of the note panel.
	$('#note').panel({
        tools: [{
            iconCls: 'icon-add',
            handler: function() {
            	noteDialogHandler('Add')
            }
        }, {
            iconCls: 'icon-edit',
            handler: function() {
            	noteDialogHandler('Edit')
            }
        }, {
            iconCls: 'icon-remove',
            handler: deleteNoteHandler
        }]
	});
	
	function noteDialogHandler(dialogType) {
		var selectedItem = getSelectedNote();
		var isShowDialog = true;
		if (dialogType == 'Edit') {
			if (selectedItem) {
//				$('#dialogNote input').val(selectedItem.find('p:eq(0)').text());
//				$('#dialogNote textarea').val(selectedItem.find('p:eq(1)').text());
				for (var i = 0; i < currentSavedNoteList.length; i++) {
					
					if (currentSavedNoteList[i].id == selectedItem.data('id')) {
						$('#dialogNote input').val(currentSavedNoteList[i].title);
						$('#dialogNote textarea').val(currentSavedNoteList[i].content);
						break;
					}
				}
			} else {
				isShowDialog = false;
				$.messager.alert('Prompt', 'Info: Select any note firstly.')
			}
		}
		if (isShowDialog) {
			$('#dialogNote').dialog({
				title: dialogType + ' note',
				width: 700,
				height: 450,
				closed: false,
				cache: false,
				modal: true,
				resizable: false,
				draggable: false,
				buttons: [{
					iconCls: 'icon-save',
					text: 'Save',
					handler: function() {
						addOrUpdateNote(dialogType)
					}
				}],
				onClose: function() {
					$("#dialogNote form").form("clear");
				}
			});
			$('#dialogNote').window('center');
		}
	}
	
	function addOrUpdateNote(actionType) {
		if (actionType == 'Add') {
			var param = {
				notebookId: getSelectedNotebook().data('id'),
				title: $('#dialogNote input').val(),
				content: $('#dialogNote textarea').val()
			};
			$.post(config['NOTE_ADD_URL'], param, function(result) {
				if (result.succeeded) {
					$("#dialogNote form").form("clear");
					$('#dialogNote').window('close');
					// Refresh note list data.
					getNoteListData(getSelectedNotebook().data('id'));
					// Refresh notebook's note sum
					var strNoteSum = getSelectedNotebook().find('span').text();
					getSelectedNotebook().find('span').text(Number(strNoteSum) + 1);
				} else {
					$.messager.alert('Prompt', 'Error: ' + result.message);
				}
			});
			
		} else if (actionType == 'Edit') {
			var param = {
				notebookId: getSelectedNotebook().data('id'),
				title: $('#dialogNote input').val(),
				content: $('#dialogNote textarea').val()
			};
			$.post(config['NOTE_UPDATE_URL'] + getSelectedNote().data('id'), param, function(result) {
				if (result.succeeded) {
					$("#dialogNote form").form("clear");
					$('#dialogNote').window('close');
					// Refresh note list data.
					getNoteListData(getSelectedNotebook().data('id'));
				} else {
					$.messager.alert('Prompt', 'Error: ' + result.message);
				}
			})
		}
	}
	
	function deleteNoteHandler() {
		var selectedItem = getSelectedNote();
		if (selectedItem) {
            $.messager.confirm('Confirm', 'Are you confirm this?', function(yes){
                if (yes){
                	$.get(config['NOTE_DELETE_URL'] + selectedItem.data('id'), function(result) {
        				if (result.succeeded) {
        					// Refresh notebook's note sum
        					var strNoteSum = getSelectedNotebook().find('span').text();
        					getSelectedNotebook().find('span').text(Number(strNoteSum) - 1);
        					// Refresh note list data.
    						getNoteListData(getSelectedNotebook().data('id'));
        				} else {
        					$.messager.alert('Prompt', 'Error: ' + result.message);
        				}
        			});
                }
            });
		} else {
			$.messager.alert('Prompt', 'Info: Select any note firstly.')
		}
	}
	
	function getSelectedNote() {
		var selectedItem = undefined;
		if (noteDiv.find('a')) {
			$.each(noteDiv.find('a'), function(index, item) {
				if ($(item).hasClass('active')) {
					selectedItem =  $(item);
				}
			});
		}
		return selectedItem;
	}
	
	function getFixedContent(content) {
		if (content.length > 100) {
			return content.substring(0, 100) + '....';
		} else {
			return content;
		}
	}
});